package com.zhugang.week01;


/**
 * @program algorithms
 * @description: defangIpaddr
 * @author: chanzhugang
 * @create: 2022/05/19 23:32
 */
public class IPDefang {

    public static void main(String[] args) {
        IPDefang ipDefang = new IPDefang();
        String str = ipDefang.defangIPaddr3("1.1.1.1");
        System.out.println(str);
    }

    /**
     * IP地址无效化
     * 目的是实现一个replace()函数
     *
     * @param address
     * @return
     */
    public String defangIPaddr1(String address) {
        int n = address.length();
        char[] temp = new char[n + 6];
        int k = 0;
        for (int i = 0; i < n; i++) {
            char c = address.charAt(i);
            if (c != '.') {
                temp[k++] = c;
            } else {
                temp[k++] = '[';
                temp[k++] = c;
                temp[k++] = ']';
            }
        }
        return new String(temp);
    }

    public String defangIPaddr2(String address) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < address.length(); i++) {
            char c = address.charAt(i);
            if (c != '.') {
                sb.append(c);
            } else {
                sb.append("[.]");
            }
        }
        return sb.toString();
    }

    public String defangIPaddr3(String address) {
        return address.replace(".", "[.]");
    }
}